package com.kaikeba.util;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: Gyx
 * @Date: 2021/2/19 18:38
 */
@WebFilter(urlPatterns = {"/*"},initParams = {
        @WebInitParam(name = "code",value = "utf-8")
})
public class FilterUtil implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器启动");
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        PrintWriter writer = response.getWriter();
        //添加和修改的学生信息过滤
        if(requestURI.endsWith("/insert")||requestURI.endsWith("/update")){
            String stuNumber = request.getParameter("stuNumber");
            String stuName = request.getParameter("stuName");
            String stuClass = request.getParameter("stuClass");
            String stuAge = request.getParameter("stuAge");
            if(stuName!=""&&stuNumber!=""&&stuClass!=""&&stuAge!=""){
                try {
                    Integer.parseInt(stuAge);
                }catch (Exception e){
                    writer.println("<script>alert('年龄必须为数字');location.href='index.jsp'</script>");
                }
                if(stuAge.length()>2){
                    writer.println("<script>alert('年龄不可超过2位数字');location.href='index.jsp'</script>");
                }else {
                    filterChain.doFilter(servletRequest,servletResponse);
                }
            }else {
                writer.println("<script>alert('学生信息不完整');location.href='index.jsp'</script>");
            }
        }else {
            filterChain.doFilter(servletRequest,servletResponse);
        }
        System.out.println("过滤器结束");
    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁");
    }
}
